package org.icnmasjid.member.webapp.action;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.icnmasjid.member.webapp.action.BaseFormController;
import org.icnmasjid.member.model.Login;
import org.icnmasjid.member.service.LoginManager;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

public class LoginFormController extends BaseFormController {
    private LoginManager loginManager = null;

    public void setLoginManager(LoginManager loginManager) {
        this.loginManager = loginManager;
    }
    public LoginFormController() {
        setCommandName("login");
        setCommandClass(Login.class);
    }

    protected Object formBackingObject(HttpServletRequest request)
    throws Exception {
        String id = request.getParameter("id");
        Login login = null;

        if (!StringUtils.isEmpty(id)) {
            login = loginManager.getLogin(id);
        } else {
            login = new Login();
        }

        return login;
    }

    public ModelAndView onSubmit(HttpServletRequest request,
                                 HttpServletResponse response, Object command,
                                 BindException errors)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("entering 'onSubmit' method...");
        }

        Login login = (Login) command;
        boolean isNew = (login.getId() == null);
        Locale locale = request.getLocale();

        if (request.getParameter("delete") != null) {
            loginManager.removeLogin(login.getId().toString());

            saveMessage(request, getText("login.deleted", locale));
        } else {
            loginManager.saveLogin(login);

            String key = (isNew) ? "login.added" : "login.updated";
            saveMessage(request, getText(key, locale));

            if (!isNew) {
                return new ModelAndView("redirect:editLogin.html", "id", login.getId());
            }
        }

        return new ModelAndView(getSuccessView());
    }
}
